package accs.model.mail;

import java.util.List;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Store;

public class MailChecker {
	private MailSettingsFetcher fetcher=new CachedMailSettingsFetcher();
	
	public MailCheckResult checkAdress(String email, String pass) {
		return checkAdress(email, pass, new DefaultMailBoxListener());
	}
	
	public MailCheckResult checkAdress(String email, String pass, MailBoxListener listener) {
		List<Properties> list=fetcher.fetchSettingsForAddress(MailSettingsFetcher.extractHost(email));
		
		if(list==null) {
			//System.out.println("no entries for: "+email);
			return MailCheckResult.UNKNOWN_SETTINGS;
		}
		
		for(Properties props : list) { System.out.println(props);
			try {
				check(email, pass, props, listener);
				return MailCheckResult.VALID;
			} catch(Exception e) {
				//System.out.println("did not work: "+props);
			}
		}
		
		return MailCheckResult.INVALID;
	}
	
	private void check(String email, String pass, Properties props, MailBoxListener listener) throws Exception {
		String type=props.getProperty("type");
		
		Properties sessionProps=new Properties();
		sessionProps.setProperty("mail."+type+".host",props.getProperty("host"));
		sessionProps.setProperty("mail."+type+".port",props.getProperty("port"));
		sessionProps.setProperty("mail."+type+".starttls.enable","true");
		
		Session session=Session.getInstance(sessionProps);
		Store store=session.getStore(type);
		store.connect(email, pass);
		
		listener.mailboxOpen(store);
		
		store.close();
	}
}